<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Cache;

class Area extends Model
{
    protected $guarded = [];
    public $timestamps = false;

    public function getAReas()
    {
        //Cache::forget('book-shop:areas:index');die;
        return Cache::remember('book-shop:areas:index', 24*60, function(){
            return $this->areasList();
        });
    }

    private function areasList()
    {
        $provinces = Area::query()->select(['id','name'])->where('pid',0)->where('type',1)->get();

        $items = [];
        if(!empty($provinces))
        {
            foreach ($provinces as $p)
            {
                $citys = Area::query()->select(['id','name'])->where('pid',$p->id)->where('type',2)->get();

                $citys_arr = [];
                if(!empty($citys))
                {
                    foreach ($citys as $c)
                    {
                        $areas = Area::query()->select(['id','name'])->where('pid',$c->id)->where('type',3)->get();
                        $areas_arr = [];
                        if(!empty($areas))
                        {
                            foreach ($areas as $a)
                            {
                                $areas_arr[] = [
                                    'id'   => $a->id,
                                    'name' => $a->name,
                                ];
                            }
                        }

                        $citys_arr[] = [
                            'id'    => $c->id,
                            'name'  => $c->name,
                            'areas' => $areas_arr
                        ];
                    }
                }


                $items[] = [
                    'id'    => $p->id,
                    'name'  => $p->name,
                    'citys' => $citys_arr
                ];
            }
        }

        $result['provinces'] = $items;
        return $result;
    }

    public function getProvinces()
    {
        //Cache::forget('book-shop:areas:provinces');die;
        return Cache::remember('book-shop:areas:provinces', 24*60, function(){
            return $this->provinceList();
        });
    }

    private function provinceList()
    {
        return $this->newQuery()->select(['id','name'])->where('pid',0)->where('type',1)->get();
    }

}
